
/*
 * Copyright (C) 2008-2009 Archie L. Cobbs. All rights reserved.
 *
 * $Id: MultiIterator.java 377 2010-03-11 20:50:18Z archie.cobbs $
 */

package org.dellroad.sidekar.util;

import java.util.Arrays;
import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * Concatenates multiple {@link Iterator}s into a single iterator.
 */
public class MultiIterator<E> implements Iterator<E> {

    final Iterator<? extends Iterator<? extends E>> iterators;

    Iterator<? extends E> current;
    boolean advanced;

    /**
     * Constructor.
     *
     * @param iterators iterators to concatentate
     */
    public MultiIterator(Iterable<? extends Iterator<? extends E>> iterators) {
        this.iterators = iterators.iterator();
    }

    /**
     * Constructor.
     *
     * @param iterators iterators to concatentate
     */
    public MultiIterator(Iterator<? extends E>[] iterators) {
        this.iterators = Arrays.asList(iterators).iterator();
    }

    public final boolean hasNext() {
        if (!this.advanced && !findNext())
            return false;
        return true;
    }

    public final E next() {
        if (!this.advanced && !findNext())
            throw new NoSuchElementException();
        E value = this.current.next();
        this.advanced = false;
        return value;
    }

    public final void remove() {
        if (this.current == null)
            throw new IllegalStateException();
        this.current.remove();
    }

    /**
     * Cycle through our iterator list until we find one with a next element.
     */
    boolean findNext() {
        while (true) {
            if (this.current == null) {
                if (!this.iterators.hasNext())
                    return false;
                this.current = this.iterators.next();
            }
            if (this.current.hasNext())
                return true;
            this.current = null;
        }
    }
}

